/**
 * Created by wenguangjia on 2017/6/16.
 */
(function () {
    'use strict';

    angular
        .module('logcenterApp')
        .controller('partitionConfigController', partitionConfigController);
    partitionConfigController.$inject = ['$scope', 'searchService', 'toaster'];
    function partitionConfigController($scope, searchService, toaster) {
        var notify = function (type, title, message) {
            toaster.pop(type, title, message);
        };
        $scope.param={cname:null,fname:null,ename:null};
        $scope.detailParam = {ip:'0.0.0.0',host:null};

        $scope.query=function(){
          $scope.gridFormOptions.dataSource.read();
        };
        $scope.clear=function(){
            $scope.param={cname:null,fname:null,ename:null};
        };

        /**
         * win
         * @type {{title: string, modal: boolean, visible: boolean}}
         */
        $scope.win = {
            title: '服务器配置',
            modal: true,
            visible: false
        };
        $scope.winOptions = {
            modal: true
        };


        /**
         *grid
         */
        var columns = [
            // {field: "id", title: "主键", hidden:true},
            {field: "fname", title: "地区", width: 150},
            {field: "cname", title: "分区名称", width: 150},
            {field: "ename", title: "分区代码", width: 150},
            {field: "code", title: "索引", width: 150},
            {field: "url", title: "平台服务API", width: 300}
        ];

        $scope.gridFormOptions = {
            selectable: "row",
            sortable: true,
            resizable: true,
            columnMenu: true,
            toolbar: [
                "create",
                {
                    name: "customEdit",
                    text: "编辑",
                    imageClass: "k-edit",
                    className: "k-custom-edit",
                    iconClass: "k-icon"
                },
                {
                    name: "customDestroy",
                    text: "删除",
                    imageClass: "k-delete",
                    className: "k-custom-delete",
                    iconClass: "k-icon"
                }
            ],
            editable: "popup",
            dataBound: function (e) {
                $scope.gridForm.select("tr:eq(0)");
            },
            columns: columns
        };
        $scope.UserModel = kendo.data.Model.define({
            id: "id",
            fields: {
                fname: {validation: {required: true}},
                cname: {validation: {required: true}},
                ename: {validation: {required: true}},
                code: {validation: {required: true}},
                url: {validation: {required: true}}
            }
        });
        $scope.gridFormOptions.dataSource = new kendo.data.DataSource({
            transport: {
                read: function (e) {
                    searchService.getPartition($scope.param).then(
                        function(resp){
                            e.success(resp.data);
                        },function(err){
                            notify('success', '成功', '查询失败'+err);
                            e.error(err);
                        }
                    )
                },
                create: function (e) {
                    //var model = new $scope.UserModel();
                    var model=e.data.models[0];
                    searchService.savePartition(model).then(function (resp) {
                        e.success();
                        notify('success', '成功', '新增成功！');
                    }, function (error) {
                        e.error(error);
                        notify('error', '失败', error);

                    });
                },
                update: function (e) {
                    var model=e.data.models[0];
                    searchService.savePartition(model).then(function (resp) {
                        notify('success', '成功', '修改成功！');
                        e.success();
                    }, function (error) {
                        e.error(error);
                        notify('error', '失败', error);
                    });
                },
                destroy: function (e) {
                    var model=e.data.models[0]
                    searchService.deletePartition(model).then(function (resp) {
                        notify('success', '成功', '删除成功！');
                        e.success();
                    }, function (error) {
                        e.error(error);
                        notify('error', '失败', error);
                    });
                },
                parameterMap: function (options, operation) {
                    if (operation !== "read" && options.models) {
                        return {models: kendo.stringify(options.models)};
                    }
                }
            },
            batch: true,
            schema: {
                model: $scope.UserModel
            }
        });


        /**
         * detailGrid
         * @type {[*]}
         */
        var detailColumns = [
            { field: "ip", title:"ip"},
            { field: "host", title:"host"}
        ];

        $scope.detailGridOptions = function(dataItem){
            $scope.fdataItem = dataItem;
            return {
                dataSource:{
                    transport: {
                        read: function (e) {
                            searchService.getPartitionIp2Host({}).then(
                                function(resp){
                                    e.success(resp.data);
                                },function(err){
                                    notify('success', '成功', '查询失败'+err);
                                    e.error(err);
                                }
                            )
                        },
                        create: function (e) {
                            //var model = new $scope.UserModel();
                            var model=e.data.models[0];
                            searchService.savePartitionIp2Host(model).then(function (resp) {
                                e.success();
                                notify('success', '成功', '新增成功！');
                            }, function (error) {
                                e.error(error);
                                notify('error', '失败', error);

                            });
                        },
                        update: function (e) {
                            var model=e.data.models[0];
                            searchService.savePartitionIp2Host(model).then(function (resp) {
                                notify('success', '成功', '修改成功！');
                                e.success();
                            }, function (error) {
                                e.error(error);
                                notify('error', '失败', error);
                            });
                        },
                        destroy: function (e) {
                            var model=e.data.models[0]
                            searchService.deletePartitionIp2Host(model).then(function (resp) {
                                notify('success', '成功', '删除成功！');
                                e.success();
                            }, function (error) {
                                e.error(error);
                                notify('error', '失败', error);
                            });
                        },
                        parameterMap: function (options, operation) {
                            if (operation !== "read" && options.models) {
                                return {models: kendo.stringify(options.models)};
                            }
                        }
                    },
                    filter: { field: "partitionId", operator: "eq", value: dataItem.id },
                    batch: true,
                    schema: {
                        model: $scope.detailModel
                    }
                },
                selectable: "row",
                sortable: true,
                resizable: true,
                columnMenu: true,
                toolbar: [
                    {
                        template: '<kendo-button  ng-click="addIp()">新增</kendo-button>'
                    },
                    {
                        template: '<kendo-button  ng-click="updateIp()">编辑</kendo-button>'
                    },
                    {
                        template: '<kendo-button  ng-click="deleteIp()">删除</kendo-button>'
                    },
                ],
                editable: "popup",
                columns: detailColumns
            }};

        $scope.detailModel = kendo.data.Model.define({
            id: "id",
            fields: {
                partitionId: {validation: {required: true}},
                ip: {validation: {required: true}},
                host: {validation: {required: true}}
            }
        });

        //监听列事件
        $scope.gridDetailRowClick = function (data, dataItem, columns) {
            $scope.detail = dataItem;
        };
        var action = '';
        $scope.addIp=function(){
            action = 'add';
            if($scope.detail){
                $scope.detail.host='';
                $scope.detail.ip='0.0.0.0';
            }
            $scope.win.open();
            $scope.win.center();
        }
        $scope.updateIp=function(){
            action = 'update';
            if(!$scope.detail){
                notify('warn', '警告', '请先选择一列');
            }else{
                $scope.win.open();
                $scope.win.center();
            }
        };
        $scope.deleteIp=function(){
            if(!$scope.detail){
                notify('warn', '警告', '请先选择一列');
            }else{
                searchService.deletePartitionIp2Host($scope.detail.id).then(function (resp) {
                    notify('success', '成功', '删除成功！');
                    $scope.gridFormOptions.dataSource.read();
                }, function (error) {
                    e.error(error);
                    notify('error', '失败', error);
                });
            }
        }

        $scope.save = function(){
            if(action == 'add'){
                var data = {partitionId:$scope.fdataItem.id,ip:$scope.detail.ip,host:$scope.detail.host};
            }else if(action == 'update'){
                var data = {id:$scope.detail.id,partitionId:$scope.detail.partitionId,ip:$scope.detail.ip,host:$scope.detail.host};
            }
            searchService.savePartitionIp2Host(data).then(function (resp) {
                $scope.win.close();
                $scope.gridFormOptions.dataSource.read();
                notify('success', '成功', '保存成功！');
            }, function (error) {
                e.error(error);
                notify('error', '失败', error);
            });


        }

        $scope.cancel = function(){
            $scope.win.close();
        }


        $scope.$on("kendoWidgetCreated", function (event, widget) {
            if (widget === $scope.gridForm) {
                widget.element.find(".k-custom-edit").on("click", function (e) {
                    e.preventDefault();
                    var selected = $scope.gridForm.select();
                    if (selected.length == 0) {
                        //alert('No record selected')
                        notify('waring', '提示', '请先选择一行！');
                    } else {
                        $scope.gridForm.editRow(selected);
                    }

                });
                widget.element.find(".k-custom-delete").on("click", function (e) {
                    e.preventDefault();
                    var selected = $scope.gridForm.select();
                    if (selected.length == 0) {
                        //alert('No record selected')
                        notify('waring', '提示', '请先选择一行！');
                    } else {
                        $scope.gridForm.removeRow(selected);
                    }

                });
            }
        });


    }


})();
